<?php

function iredirect($url, $timeout=0, $noroot = false) {
	global $root;
	if (substr($url,0,4)=="http") $noroot = true;
	if ($noroot) $r = ""; else $r = $root."/";
	if ($timeout==0) {
		Page::Script("document.location='{$r}{$url}';");
	}else{
		Page::Script("setTimeout(\"document.location='{$r}{$url}';\", {$timeout});");
	}
}

function getFirstSubValue($arr, $subkey, $subval, $get = null) { foreach ($arr as $k) if ($k[$subkey]==$subval) return $get ? $k[$get] : $k; }

function getReferer() {
	return $_SERVER['HTTP_REFERER'];
}

function getSamePageWithCustomQueryString($querystring) {
	// linkreq
	global $cl;
	$query = $_GET;
	if (is_array($querystring)) {
		$queryadd = $querystring;
	}else{
		$queryadd = array();
		parse_str($querystring, $queryadd);
	}
	$newquery = array_merge($query, $queryadd);
	return $cl["proto"]."://".$cl["domain"].$cl["portadd"].$cl["relurl"]."/".$cl['linkreq']."?".http_build_query($newquery);
}

function getCurrentRequestURL() {
	global $cl;
	return $cl["proto"]."://".$cl["domain"].$cl["portadd"].$cl["relurl"]."/".$cl['linkreq'];
}

function getBackHere($url='no') {
	if ($url===false) unset($_SESSION['getbackurl']);
	else $_SESSION['getbackurl'] = ($url=='no') ? $url : getCurrentRequestURL();
}

function gotoLastPlace() {
	if ($_SESSION['getbackurl'])
		iredirect($_SESSION['getbackurl'], 1000, true);
	else
		return false;
}

// checks for http url :D bad naming, very bad
function is_url($code) {
	$code = trim($code);
	return (substr($code,0,4)=='http') ? true : false;
}

function getFileExtension($filename) {
	$filename = basename($filename);
	$i=0;
	while ($char!=".") {
		$i = $i + 1;
		$char = substr($filename, -$i, 1);
	}
	$afterDot = substr($filename, -$i);
	return $afterDot;
}

// $fname = "/srv/hosts/abc.jpg";
// $newname = "abc_2"

function changeJustFilenameNotTheExtension($fname, $newname) {
	$filename = basename($fname);
	$path = dirname($fname);
	$char="";
	$i=0;
	while ($char!=".") {
		$i = $i + 1;
		$char = substr($filename, -$i, 1);
	}
	$afterDot = substr($filename, -$i);
	$beforeDot = substr($filename, 0, -$i);
	$newname = str_replace("%%", $beforeDot, $newname);
	$newfilename = $path."/".$newname.$afterDot;
	
	
	return $newfilename;
}

//BBcode 2 HTML was written by WAY2WEB.net

function BBCode($Text)
    {
      // Replace any html brackets with HTML Entities to prevent executing HTML or script
         // Don't use strip_tags here because it breaks [url] search by replacing & with amp
         $Text = str_replace("<", "&lt;", $Text);
         $Text = str_replace(">", "&gt;", $Text);

         // Convert new line chars to html <br /> tags
         $Text = nl2br($Text);

         // Set up the parameters for a URL search string
         $URLSearchString = " a-zA-Z0-9\:\/\-\@\?\&\.\=\_\~\#\'";
         // Set up the parameters for a MAIL search string
         $MAILSearchString = $URLSearchString . " a-zA-Z0-9\.@";

         // Perform URL Search
         $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/", '<a href="$1" target="_blank">$1</a>', $Text);
         $Text = preg_replace("(\[url\=([$URLSearchString]*)\](.+?)\[/url\])", '<a href="$1" target="_blank">$2</a>', $Text);
      //$Text = preg_replace("(\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[/url\])", '<a href="$1" target="_blank">$2</a>', $Text);

         // Perform MAIL Search
         $Text = preg_replace("(\[mail\]([$MAILSearchString]*)\[/mail\])", '<a href="mailto:$1">$1</a>', $Text);
         $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.+?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);

         // Check for paragraph
         $Text = preg_replace("(\[p\](.+?)\[\/p])is",'<p>$1</p>',$Text);
      
         // Check for bold text
         $Text = preg_replace("(\[b\](.+?)\[\/b])is",'<span class="bold">$1</span>',$Text);

		 // Langhelper
         $Text = preg_replace("(\[lh\](.+?)\[\/lh])is",'<span class="langhelper">$1</span>',$Text);

		 // Arabic
         $Text = preg_replace("(\[arabic\](.+?)\[\/arabic])is",'<span class="arabic">$1</span>',$Text);

         // Check for Italics text
         $Text = preg_replace("(\[i\](.+?)\[\/i\])is",'<span class="italics">$1</span>',$Text);

         // Check for Underline text
         $Text = preg_replace("(\[u\](.+?)\[\/u\])is",'<span class="underline">$1</span>',$Text);

         // Check for strike-through text
         $Text = preg_replace("(\[s\](.+?)\[\/s\])is",'<span class="strikethrough">$1</span>',$Text);

         // Check for over-line text
         $Text = preg_replace("(\[o\](.+?)\[\/o\])is",'<span class="overline">$1</span>',$Text);

         // Check for colored text
         $Text = preg_replace("(\[color=(.+?)\](.+?)\[\/color\])is","<span style=\"color: $1\">$2</span>",$Text);

         // Check for sized text
         $Text = preg_replace("(\[size=(.+?)\](.+?)\[\/size\])is","<span style=\"font-size: $1px\">$2</span>",$Text);

         // Check for list text
         $Text = preg_replace("/\[list\](.+?)\[\/list\]/is", '<ul class="listbullet">$1</ul>' ,$Text);
         $Text = preg_replace("/\[list=1\](.+?)\[\/list\]/is", '<ul class="listdecimal">$1</ul>' ,$Text);
         $Text = preg_replace("/\[list=i\](.+?)\[\/list\]/s", '<ul class="listlowerroman">$1</ul>' ,$Text);
         $Text = preg_replace("/\[list=I\](.+?)\[\/list\]/s", '<ul class="listupperroman">$1</ul>' ,$Text);
         $Text = preg_replace("/\[list=a\](.+?)\[\/list\]/s", '<ul class="listloweralpha">$1</ul>' ,$Text);
         $Text = preg_replace("/\[list=A\](.+?)\[\/list\]/s", '<ul class="listupperalpha">$1</ul>' ,$Text);
         $Text = str_replace("[*]", "<li>", $Text);

         // Check for font change text
         $Text = preg_replace("(\[font=(.+?)\](.+?)\[\/font\])","<span style=\"font-family: $1;\">$2</span>",$Text);

         // Declare the format for [code] layout
         $CodeLayout = '<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                             <tr>
                                 <td class="quotecodeheader"> Code:</td>
                             </tr>
                             <tr>
                                 <td class="codebody">$1</td>
                             </tr>
                        </table>';
         // Check for [code] text
         $Text = preg_replace("/\[code\](.+?)\[\/code\]/is","$CodeLayout", $Text);
         // Declare the format for [php] layout
         $phpLayout = '<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                             <tr>
                                 <td class="quotecodeheader"> Code:</td>
                             </tr>
                             <tr>
                                 <td class="codebody">$1</td>
                             </tr>
                        </table>';
         // Check for [php] text
         $Text = preg_replace("/\[php\](.+?)\[\/php\]/is",$phpLayout, $Text);

         // Declare the format for [quote] layout
         $QuoteLayout = '<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                             <tr>
                                 <td class="quotecodeheader"> Quote:</td>
                             </tr>
                             <tr>
                                 <td class="quotebody">$1</td>
                             </tr>
                        </table>';
                  
         // Check for [quote] text
         $Text = preg_replace("/\[quote\](.+?)\[\/quote\]/is","$QuoteLayout", $Text);
      
         // Images
         // [img]pathtoimage[/img]
         $Text = preg_replace("/\[img\](.+?)\[\/img\]/", '<img src="$1">', $Text);
      
         // [img=widthxheight]image source[/img]
         $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.+?)\[\/img\]/", '<img src="$3" height="$2" width="$1">', $Text);
      
        return $Text;
   }

function print_rn($mixed) {
	ob_start();
	print_r($mixed);
	$a = ob_get_contents();
	ob_end_clean();
	return $a;
}

function email_validate($email) {
	return (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email));
}

/* function from : http://code.web-max.ca/misc_htmlemail.php */
function email_sendHTML($HTML, $from, $to, $subject) {
    $headers = "From: $from\r\n"; 
    $headers .= "MIME-Version: 1.0\r\n";
    $boundary = uniqid("HTMLEMAIL"); 
    
// First we be nice and send a non-html version of our email
    
    $headers .= "Content-Type: multipart/alternative;".
                "boundary = $boundary\r\n\r\n"; 

    $headers .= "This is a MIME encoded message.\r\n\r\n"; 

    $headers .= "--$boundary\r\n".
                "Content-Type: text/plain; charset=UTF-8\r\n".
                "Content-Transfer-Encoding: base64\r\n\r\n"; 
                
    $headers .= chunk_split(base64_encode(strip_tags($HTML))); 

// Now we attach the HTML version

    $headers .= "--$boundary\r\n".
                "Content-Type: text/html; charset=UTF-8\r\n".
                "Content-Transfer-Encoding: base64\r\n\r\n"; 
                
    $headers .= chunk_split(base64_encode($HTML)); 

// And then send the email ....
	//$subject= mb_encode_mimeheader($subject,"UTF-8", "B", "\n");
    $subject = encodeBase64($subject);

return mail($to,$subject,"",$headers);   
}

function encodeBase64($string, $charset = 'UTF-8') {
	$m=preg_match_all('/(\w*[\x80-\xFF]+\w*)/', $string, $matches);
	if($m) return "=?" . $charset . "?B?" . @base64_encode($string) . "?=";
	else return $string;
}

//test:
//echo destroyHTMLClass("abicim <span class=\"arabic\">sana naber</span> diyorum", 'arabic', false);
function destroyHTMLClass($txt, $class, $destroyText = false) {
	$match = "#<([^\s]+)[^>]*class=(['\"]{1}).*{$class}.*\\2[^>.]*>(.*)<\/(\\1)>#iUs";
	if (!$destroyText)
		return preg_replace($match, "\\3", $txt);
	else
		return preg_replace($match, "", $txt);
}

// test
//echo destroyTagAttr("sdafer<span class='naber' style=\"margin:auto;\">asdcasc</span>", "span", "style");
//echo "\n\n";
//echo destroyTagAttr("<p style=\"margin-bottom: 3pt; text-align: center\" align=\"left\">O vakit, kendilerine uyulan kimseler, kendilerine uyanlardan hızla ka&ccedil;ıp uzaklaşmış ve azabı", "p", "style");
function destroyTagAttr($html, $tag, $attr) {
	$match = "#<({$tag}\ [^>]*){$attr}=(['\"]{1}).*\\2([^>]*)>#iUs";
	return preg_replace($match, "<\\1\\3>", $html);
}

function arrayFindIndex($arr, $indkey, $indval) {
	if (!is_array($arr)) return false;
	for ($i=0;$i<sizeof($arr);$i++)
		if ($arr[$i][$indkey]==$indval) return $i;
}

// thanks to http://www.lastfm.pl/user/TheMariner
function mb_unserialize($serial_str) {
	$out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
	return unserialize($out);
}

function findText($start_limiter,$end_limiter,$string) {
		echo "<hr />";
		$start_pos = strpos($haystack,$start_limiter);
		if ($start_pos === FALSE)
			return FALSE;	
		
		$end_pos = strpos($haystack,$end_limiter,$start_pos);
		
		if ($end_pos === FALSE)
			return FALSE;
		
		var_dump($haystack);
		echo "<hr />";
		return substr($haystack, $start_pos+1, ($end_pos-1)-$start_pos);
}

function saveLastPage() {
	global $cl;
	$url = getSamePageWithCustomQueryString(array());
	if (preg_match("/^(user|ajax)/", $cl['linkreq'])) return false;	// user app or ajax call
	if ($cl['method']=="POST") return false;		// postlu adresleri alma
	$_SESSION['lastpage'] = $url;
}

function gotoLastPage() {
	if ($url = $_SESSION['lastpage']) redirect($url);
}

?>